<template>
  <div class="w-64 border-r border-gray-200 p-3">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-base font-medium">接口集合</h3>
      <n-button size="small" @click="openCreateModal">
        新建集合
      </n-button>
    </div>

    <n-tree block-line :data="treeData" :default-expanded-keys="defaultExpandedKeys"
      @update:selected-keys="handleTreeSelect" @contextmenu="(e, node) => handleContextMenu(e as MouseEvent, node)">
    </n-tree>

    <!-- 添加右键菜单 -->
    <n-dropdown
      :show="showDropdown"
      :x="dropdownX"
      :y="dropdownY"
      :options="dropdownOptions"
      placement="bottom-start"
      @select="handleDropdownSelect"
      @clickoutside="handleClickOutside"
    />

    <!-- 创建集合的模态框 -->
    <n-modal v-model:show="showCreateModal">
      <n-card style="width: 500px" title="新建集合" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <n-form ref="formRef" :model="formModel" :rules="rules">
          <n-form-item label="集合名称" path="name">
            <n-input v-model:value="formModel.name" placeholder="请输入集合名称" />
          </n-form-item>
          <n-form-item label="描述" path="description">
            <n-input v-model:value="formModel.description" type="textarea" placeholder="请输入集合描述" />
          </n-form-item>
          <n-form-item label="父级集合" path="parentId">
            <n-tree-select v-model:value="formModel.parentId" :options="treeData" placeholder="请选择父级集合" clearable />
          </n-form-item>
        </n-form>

        <template #footer>
          <div class="flex justify-end gap-2">
            <n-button @click="showCreateModal = false">取消</n-button>
            <n-button type="primary" :loading="loading" @click="submitCreateCollection">
              确定
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { NButton, NTree, NModal, NCard, NForm, NFormItem, NInput, NTreeSelect, NDropdown } from 'naive-ui'
import type { TreeOption, FormRules, FormInst } from 'naive-ui'
import { GetApiGroups, AddApiGroup } from '../../wailsjs/go/apis/Apis'

const emit = defineEmits<{
  (e: 'select', groupId: number, groupName: string): void
}>()

const showCreateModal = ref(false)
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const treeData = ref<TreeOption[]>([])
const defaultExpandedKeys = ref<string[]>([])

const formModel = ref({
  name: '',
  description: '',
  parentId: null as number | null
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入集合名称', trigger: 'blur' }
  ]
}

const showDropdown = ref(false)
const dropdownX = ref(0)
const dropdownY = ref(0)
const currentNode = ref<TreeOption | null>(null)

const dropdownOptions = [
  {
    label: '添加子目录',
    key: 'add-folder'
  },
  {
    label: '添加接口',
    key: 'add-api'
  },  
  {
    label: '重命名',
    key: 'rename'
  },
  {
    label: '删除',
    key: 'delete'
  }
]

const handleDropdownSelect = (key: string) => {
  if (!currentNode.value) return
  
  switch (key) {
    case 'add-folder':
      formModel.value.parentId = parseInt(currentNode.value.key as string)
      showCreateModal.value = true
      break
    case 'add-api':
      // TODO: 实现添加接口的逻辑
      break
    case 'delete':
      // TODO: 实现删除的逻辑
      break
  }
}

// 加载集合列表
const loadCollections = async () => {
  try {
    const collections = await GetApiGroups()
    const map = new Map<number, TreeOption>()
    const result: TreeOption[] = []

    collections.forEach(col => {
      map.set(col.ID, {
        key: col.ID.toString(),
        label: col.name,
        children: [],
        data: col
      })
    })

    collections.forEach(col => {
      const node = map.get(col.ID)!
      if (col.parent_id === 0) {
        result.push(node)
      } else {
        const parent = map.get(col.parent_id)
        if (parent) {
          parent.children = parent.children || []
          parent.children.push(node)
        }
      }
    })
    treeData.value = result
  } catch (error) {
    console.error('加载集合失败:', error)
  }
}

// 处理树节点选择
const handleTreeSelect = (keys: string[]) => {
  if (keys.length > 0) {
    const selectedId = parseInt(keys[0])
    // 从 treeData 中查找选中节点的名称
    const findNodeName = (nodes: TreeOption[]): string => {
      for (const node of nodes) {
        if (node.key === keys[0]) {
          return node.label as string
        }
        if (node.children) {
          const found = findNodeName(node.children)
          if (found) return found
        }
      }
      return ''
    }
    const selectedName = findNodeName(treeData.value)
    emit('select', selectedId, selectedName)
  }
}

// 添加打开模态框的方法
const openCreateModal = () => {
  showCreateModal.value = true
}

// 修改提交方法名称，避免混淆
const submitCreateCollection = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    await AddApiGroup(formModel.value.name, formModel.value.parentId || 0)

    // 重新加载集合列表
    await loadCollections()

    // 重置表单并关闭模态框
    formModel.value = {
      name: '',
      description: '',
      parentId: null
    }
    showCreateModal.value = false

  } catch (error) {
    console.error('创建集合失败:', error)
  } finally {
    loading.value = false
  }
}

// 修改 NTree 组件，添加右键菜单相关属性
const handleContextMenu = (e: MouseEvent, node: TreeOption) => {
  e.preventDefault()
  showDropdown.value = false
  currentNode.value = node
  dropdownX.value = e.clientX
  dropdownY.value = e.clientY
  showDropdown.value = true
}

// 添加点击其他区域关闭菜单的处理
const handleClickOutside = () => {
  showDropdown.value = false
}

onMounted(() => {
  loadCollections()
})
</script>